﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Composite.Events;
using Might.Infrastructure.Annotations.Graphics;
using Might.Infrastructure.DOM;
using Might.Infrastructure.Services;
using Might.Modelica.Annotations.Graphics;

namespace Might.Modelica.Annotations {
    /// <summary>
    /// Transform data from AST format to Editor format, see <c>Might.Infrastructure.Editor</c> namespace.
    /// </summary>
    public class IconProvider : IIconProvider {
    
        //private Ast ast;
        private readonly Dictionary<IDomNode, IGraphicsAnnotation> adaptedNodes;

        /// <summary>
        /// Initializes a new instance of the <see cref="IconProvider"/> class. Needs reference of AST.
        /// </summary>
        public IconProvider() {
            adaptedNodes = new Dictionary<IDomNode, IGraphicsAnnotation>();
        }

        /// <summary>
        /// Gets the graphics annotation of requested node from DOM Item.
        /// </summary>
        /// <param name="node">DOM Node which contains graphics annotation.</param>
        /// <returns>Requested graphics annotation</returns>
        public IGraphicsAnnotation GetGraphicsAnnotation( IDomNode node ) {

            if( adaptedNodes.ContainsKey( node ) ) {
                return adaptedNodes[node];
            }

            IDomNode anotNode = node.GetFirstChild(GroupNames.Annotations);
            IGraphicsAnnotation annotation = null;

            if (anotNode != null) {
                annotation = CreateGraphicsAnnotation(anotNode, node.GetReferences());
                adaptedNodes.Add(node, annotation);
            }                       
            
            return annotation;
        }

        /// <summary>
        /// Creates the graphics annotation from DOM node.
        /// </summary>
        /// <param name="domNode">The ast node which contains graphics annotation.</param>
        /// <param name="references"></param>
        /// <returns>
        /// Graphics annotation, see <c>IGraphicsAnnotation</c> interface.
        /// </returns>
        private IGraphicsAnnotation CreateGraphicsAnnotation(IDomNode domNode, IEnumerable<IDomReference> references) {

            Icon icon = domNode.GetFirstChild(GroupNames.Icons) as Icon;
            if (icon == null) {
                icon = new Icon();
                domNode.InsertChild(GroupNames.Icons, icon);
            }

            List<IGraphicsAnnotation> list = new List<IGraphicsAnnotation>();
            // TODO references doesn't work right now
            foreach (IDomReference refNode in references) {
                list.Add(GetGraphicsAnnotation(refNode.Reference));
            }

            return new GraphicsAnnotation(icon.Children, list );
        }
    }
}